package com.lou.springboot.controller.common;

import com.alibaba.fastjson.JSONObject;
import com.lou.springboot.common.ResultVO;
import com.lou.springboot.common.ResultVOUtil;
import com.lou.springboot.config.YiDunConfig;
import com.lou.springboot.utils.HttpClient4Utils;
import com.lou.springboot.utils.JsonUtils;
import com.lou.springboot.utils.PasswordUtils;
import com.lou.springboot.utils.SignatureUtils;
import org.apache.http.Consts;
import org.apache.http.client.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/common")
public class MessageController {

    @Autowired
    private YiDunConfig yiDunConfig;

    /**
     * 实例化HttpClient，发送http请求使用，可根据需要自行调参
     */
    private static HttpClient httpClient = HttpClient4Utils.createHttpClient(100, 20, 10000, 2000, 2000);
    @PostMapping("message")
    @ResponseBody
    public ResultVO sendMessage(@RequestParam("mobile") String mobile,
                                @RequestParam("verifyCode") String verifyCode,
                                HttpSession session){
        if (StringUtils.isEmpty(mobile)) {
            return ResultVOUtil.error("手机号码不能为空");
        }
//        String kaptchaCode = session.getAttribute("verifyCode") + "";
//        if (StringUtils.isEmpty(kaptchaCode) || !verifyCode.equals(kaptchaCode)) {
//            return ResultVOUtil.error("验证码错误");
//        }
        Boolean isDev = true;
        if (isDev) {
            String result = "{\"code\":200,\"msg\":\"ok\",\"data\":{\"result\":200,\"requestId\":\"f79e04ab7c0249ca8d2250c24de671b1\"}}";
            JSONObject resultObj = JSONObject.parseObject(result);
            session.setAttribute("serverRequestId", resultObj.getJSONObject("data").getString("requestId"));
            return ResultVOUtil.success();
        } else {
            try {
                String code = PasswordUtils.generateRandomNumber(6);
                // 模板参数对应的json格式数据,例如模板为您的验证码为${p1},请于${p2}时间登陆到我们的服务器
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("code", code);
                String params = jsonObject.toJSONString();
                Map<String, String> datas = buildParam(mobile, params);
                String result = HttpClient4Utils.sendPost(httpClient, yiDunConfig.getApiUrl(), datas, Consts.UTF_8);
                System.out.println("result = [" + result + "]");
                JSONObject resultObj = JSONObject.parseObject(result);

                // 设置session
                session.setAttribute("serverRequestId", resultObj.getJSONObject("data").getString("requestId"));
                session.setAttribute("code", code);
                return ResultVOUtil.success();
            } catch (IOException e) {
                System.out.println("获取验证码失败");
                return ResultVOUtil.error("获取验证码失败");
            }
        }
    }

    private Map<String, String> buildParam(String mobile, String params) throws IOException{
        Map<String,String> map = new HashMap<>();
        map.put("businessId", yiDunConfig.getBusinessId());
        map.put("timestamp", String.valueOf(System.currentTimeMillis()));
        map.put("version", "v2");
        // 此处用申请通过的模板id
        map.put("templateId", yiDunConfig.getTemplateId());
        map.put("mobile", mobile);
        // 国际短信对应的国际编码(非国际短信接入请注释掉该行代码)
        // map.put("internationalCode", "对应的国家编码");
        map.put("paramType", "json");
        map.put("params", params);
        map.put("nonce", UUID.randomUUID().toString().replace("-", ""));
        map.put("secretId", yiDunConfig.getSecretId());
        String sign = SignatureUtils.genSignature(yiDunConfig.getSecretKey(), map);
        map.put("signature", sign);
        return map;
    }
}
